<template>
  <div class="admin-service-request-panel">
    <div class="panel-header">
      <h2>服务申请管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="loadServiceRequests">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="filters.status" placeholder="选择状态" clearable @change="handleFilterChange">
            <el-option label="全部" value="" />
            <el-option label="待处理" value="PENDING" />
            <el-option label="处理中" value="IN_PROGRESS" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filters.urgencyLevel" placeholder="选择紧急程度" clearable @change="handleFilterChange">
            <el-option label="全部" value="" />
            <el-option label="一般" value="GENERAL" />
            <el-option label="紧急" value="URGENT" />
            <el-option label="非常紧急" value="VERY_URGENT" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索联系人/设备信息"
            clearable
            @input="handleFilterChange"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="resetFilters">重置筛选</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 服务申请列表 -->
    <div class="table-section">
      <el-table
        :data="filteredServiceRequests"
        v-loading="loading"
        row-key="id"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="工单号" width="80" />
        <el-table-column prop="contactPerson" label="联系人" width="100" />
        <el-table-column prop="contactPhone" label="联系电话" width="120" />
        <el-table-column prop="deviceInfo" label="设备信息" width="200" show-overflow-tooltip />
        <el-table-column prop="urgencyLevel" label="紧急程度" width="100">
          <template #default="scope">
            <el-tag
              v-if="scope.row && scope.row.urgencyLevel === 'GENERAL'"
              type="info"
              size="small"
            >
              一般
            </el-tag>
            <el-tag
              v-else-if="scope.row && scope.row.urgencyLevel === 'URGENT'"
              type="warning"
              size="small"
            >
              紧急
            </el-tag>
            <el-tag
              v-else-if="scope.row && scope.row.urgencyLevel === 'VERY_URGENT'"
              type="danger"
              size="small"
            >
              非常紧急
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag
              v-if="scope.row && scope.row.status === 'PENDING'"
              type="warning"
              size="small"
            >
              待处理
            </el-tag>
            <el-tag
              v-else-if="scope.row && scope.row.status === 'IN_PROGRESS'"
              type="primary"
              size="small"
            >
              处理中
            </el-tag>
            <el-tag
              v-else-if="scope.row && scope.row.status === 'COMPLETED'"
              type="success"
              size="small"
            >
              已完成
            </el-tag>
            <el-tag
              v-else-if="scope.row && scope.row.status === 'CANCELLED'"
              type="info"
              size="small"
            >
              已取消
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="appointmentTime" label="预约时间" width="150">
          <template #default="scope">
            {{ scope.row ? formatDateTime(scope.row.appointmentTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="申请时间" width="150">
          <template #default="scope">
            {{ scope.row ? formatDateTime(scope.row.createdAt) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="viewServiceDetail(scope.row)"
            >
              查看详情
            </el-button>
            <el-button
              v-if="scope.row && scope.row.status === 'PENDING'"
              type="success"
              size="small"
              @click="startService(scope.row)"
            >
              开始处理
            </el-button>
            <el-button
              v-if="scope.row && scope.row.status === 'IN_PROGRESS'"
              type="warning"
              size="small"
              @click="completeService(scope.row)"
            >
              完成服务
            </el-button>
            <el-button
              v-if="scope.row && scope.row.status === 'PENDING'"
              type="danger"
              size="small"
              @click="cancelService(scope.row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 服务申请详情对话框 -->
    <el-dialog
      v-model="serviceDetailDialogVisible"
      title="服务申请详情"
      width="600px"
      @close="selectedService = null"
    >
      <div v-if="selectedService" class="service-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单号">{{ selectedService ? selectedService.id : '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ selectedService ? selectedService.contactPerson : '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedService ? selectedService.contactPhone : '-' }}</el-descriptions-item>
          <el-descriptions-item label="服务地址">{{ selectedService ? selectedService.serviceAddress : '-' }}</el-descriptions-item>
          <el-descriptions-item label="设备信息" :span="2">{{ selectedService ? selectedService.deviceInfo : '-' }}</el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="2">{{ selectedService ? selectedService.problemDescription : '-' }}</el-descriptions-item>
          <el-descriptions-item label="紧急程度">
            <el-tag
              v-if="selectedService && selectedService.urgencyLevel === 'GENERAL'"
              type="info"
            >
              一般
            </el-tag>
            <el-tag
              v-else-if="selectedService && selectedService.urgencyLevel === 'URGENT'"
              type="warning"
            >
              紧急
            </el-tag>
            <el-tag
              v-else-if="selectedService && selectedService.urgencyLevel === 'VERY_URGENT'"
              type="danger"
            >
              非常紧急
            </el-tag>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag
              v-if="selectedService && selectedService.status === 'PENDING'"
              type="warning"
            >
              待处理
            </el-tag>
            <el-tag
              v-else-if="selectedService && selectedService.status === 'IN_PROGRESS'"
              type="primary"
            >
              处理中
            </el-tag>
            <el-tag
              v-else-if="selectedService && selectedService.status === 'COMPLETED'"
              type="success"
            >
              已完成
            </el-tag>
            <el-tag
              v-else-if="selectedService && selectedService.status === 'CANCELLED'"
              type="info"
            >
              已取消
            </el-tag>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ selectedService ? formatDateTime(selectedService.appointmentTime) : '-' }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ selectedService ? formatDateTime(selectedService.createdAt) : '-' }}</el-descriptions-item>
          <el-descriptions-item v-if="selectedService && selectedService.completedBy" label="完成人">
            {{ getCompletedByUser(selectedService.completedBy) }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedService && selectedService.completedAt" label="完成时间">
            {{ formatDateTime(selectedService.completedAt) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Search } from '@element-plus/icons-vue'
import { adminAPI } from '../services/api.js'

export default {
  name: 'AdminServiceRequestPanel',
  components: {
    Refresh,
    Search
  },
  setup() {
    const loading = ref(false)
    const serviceRequests = ref([])
    const serviceDetailDialogVisible = ref(false)
    const selectedService = ref(null)
    const userCache = new Map()

    // 确保数据不为null
    const safeServiceRequests = computed(() => serviceRequests.value || [])

    // 筛选条件
    const filters = reactive({
      status: '',
      urgencyLevel: '',
      keyword: ''
    })

    // 计算属性：过滤后的服务申请
    const filteredServiceRequests = computed(() => {
      let filtered = safeServiceRequests.value

      if (filters.status) {
        filtered = filtered.filter(item => item.status === filters.status)
      }

      if (filters.urgencyLevel) {
        filtered = filtered.filter(item => item.urgencyLevel === filters.urgencyLevel)
      }

      if (filters.keyword) {
        const keyword = filters.keyword.toLowerCase()
        filtered = filtered.filter(item => 
          item.contactPerson.toLowerCase().includes(keyword) ||
          item.deviceInfo.toLowerCase().includes(keyword) ||
          item.problemDescription.toLowerCase().includes(keyword)
        )
      }

      return filtered
    })

    // 加载服务申请列表
    const loadServiceRequests = async () => {
      loading.value = true
      try {
        console.log('开始加载所有服务申请...')
        const data = await adminAPI.getAllServiceRequests()
        console.log('服务申请数据:', data)
        serviceRequests.value = data || []
        console.log('服务申请加载完成，共', serviceRequests.value.length, '条记录')
      } catch (error) {
        console.error('加载服务申请失败:', error)
        ElMessage.error('加载服务申请失败：' + error.message)
        serviceRequests.value = []
      } finally {
        loading.value = false
      }
    }

    // 查看服务申请详情
    const viewServiceDetail = (service) => {
      selectedService.value = service
      serviceDetailDialogVisible.value = true
    }

    // 开始处理服务
    const startService = async () => {
      try {
        await ElMessageBox.confirm('确定要开始处理这个服务申请吗？', '确认操作', {
          type: 'warning'
        })
        
        // 这里应该调用API更新状态
        ElMessage.success('服务申请已开始处理')
        await loadServiceRequests()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败：' + error.message)
        }
      }
    }

    // 完成服务
    const completeService = async () => {
      try {
        await ElMessageBox.confirm('确定要完成这个服务申请吗？', '确认操作', {
          type: 'warning'
        })
        
        // 这里应该调用API更新状态
        ElMessage.success('服务申请已完成')
        await loadServiceRequests()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败：' + error.message)
        }
      }
    }

    // 取消服务
    const cancelService = async () => {
      try {
        await ElMessageBox.confirm('确定要取消这个服务申请吗？', '确认操作', {
          type: 'warning'
        })
        
        // 这里应该调用API更新状态
        ElMessage.success('服务申请已取消')
        await loadServiceRequests()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败：' + error.message)
        }
      }
    }

    // 筛选条件变化处理
    const handleFilterChange = () => {
      // 筛选逻辑在computed中处理
    }

    // 重置筛选条件
    const resetFilters = () => {
      filters.status = ''
      filters.urgencyLevel = ''
      filters.keyword = ''
    }

    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 获取完成人信息
    const getCompletedByUser = (userId) => {
      const user = userCache.get(userId)
      return user ? user.nickname || user.username : `用户${userId}`
    }

    // 组件挂载时加载数据
    onMounted(() => {
      loadServiceRequests()
    })

    return {
      loading,
      serviceRequests,
      serviceDetailDialogVisible,
      selectedService,
      filters,
      safeServiceRequests,
      filteredServiceRequests,
      loadServiceRequests,
      viewServiceDetail,
      startService,
      completeService,
      cancelService,
      handleFilterChange,
      resetFilters,
      formatDateTime,
      getCompletedByUser
    }
  }
}
</script>

<style scoped>
.admin-service-request-panel {
  padding: 20px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.panel-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.service-detail {
  padding: 10px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .panel-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .filter-section .el-row {
    flex-direction: column;
  }
  
  .filter-section .el-col {
    width: 100% !important;
    margin-bottom: 10px;
  }
}
</style>
